package com.sweet.fourtimeoa.interceptor;

import com.sweet.fourtimeoa.properties.JwtProperties;
import com.sweet.fourtimeoa.util.BaseContext;
import com.sweet.fourtimeoa.util.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.HandlerInterceptor;
@Component
@Slf4j
public class JwtTokenInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtProperties jwtProperties;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //添加这行代码，让OPTIONS请求通过
        if (request.getMethod().equals("OPTIONS")) {
            return true;
        }
        String token = request.getHeader(jwtProperties.getTokenName());
        if (token == null){
            response.setStatus(401);
            return false;
        }
        try {
            Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminKey(), token);
            //时间过期
            if (claims.getExpiration().before(new java.util.Date())){
                response.setStatus(401);
                return false;
            }
            Long userId = Long.valueOf(claims.get("userId").toString());
            //设置当前线程的id
            BaseContext.setCurrentId(userId);
        } catch (NumberFormatException e) {
            response.setStatus(401);
            return false;
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
       BaseContext.removeCurrentId();
    }
}
